<template>
  <div class="dashboard-root" style="background: url('@/assets/welcom-bg.jpg') no-repeat center center fixed; background-size: cover;">
    <!-- 基金类型选择和基本信息 -->
    <div class="row m-0 p-0">
      <div class="col-12 p-0 m-0">
        <div class="d-flex justify-content-between align-items-center flex-wrap p-0 m-0">
          <!-- 基金类型选择 -->
          <div class="fund-type-selector me-4">
            <select class="form-select bg-dark text-light border-secondary" v-model="currentFundType" style="color:#eee; background-color: rgba(36, 39, 47, 0.8)!important;">
              <option v-for="type in fundTypes" :key="type" :value="type">{{ type }}</option>
            </select>
          </div>
          
          <!-- 基金基本信息 -->
          <div class="fund-info d-flex align-items-center flex-wrap" v-if="fundInfo">
            <div class="fund-info-item me-4">
              <span class="text-muted me-2" style="color:#ccc !important;">基金代码</span>
              <span class="text-primary fs-5" style="color:#fff !important;">{{ fundInfo.ts_code }}</span>
            </div>
            <div class="fund-info-item me-4">
              <span class="text-muted me-2" style="color:#ccc !important;">基金名称</span>
              <span class="text-white fs-5" style="color:#fff !important;">{{ fundInfo.fund_name }}</span>
            </div>
            <div class="fund-info-item me-4">
              <span class="text-muted me-2" style="color:#ccc !important;">基金类别</span>
              <span class="text-success fs-5" style="color:#fff !important;">{{ fundInfo.category }}</span>
            </div>
            <!-- Add to Favorites Button -->
            <button class="btn btn-outline-primary btn-sm" @click="addToFavorites">
              添加到自选
            </button>
          </div>
          
          <!-- 时间区间选择 -->
          <div class="time-controls">
            <div class="btn-group" role="group">
              <button 
                v-for="(label, interval) in timeIntervals" 
                :key="interval"
                type="button" 
                class="btn btn-outline-secondary"
                :class="{ active: currentInterval === interval }"
                @click="setInterval(interval)"
              >
                {{ label }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="row m-0 p-0">
      <div class="col-12 p-0 m-0">
        <div class="card bg-dark border-secondary m-0 p-0" style="background-color: rgba(36, 39, 47, 0.8)!important; border-color: #555!important;">
          <div class="card-header border-secondary p-0 m-0" style="border-color: #555!important;">
            <h5 class="card-title mb-0 d-flex justify-content-between align-items-center">
              <span style="color:#eee;">K线蜡烛与成交量</span>
              <button class="btn btn-outline-secondary btn-sm" @click="resetKlineZoom">重置缩放</button>
            </h5>
          </div>
          <div class="card-body p-0 m-0">
            <div ref="chartRef" style="width:100%;height:600px;"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import fundApi from '@/api/fund';
import { useRoute } from 'vue-router';
import axios from 'axios'; // Assuming axios is used for API calls
// Need to create or import a favorites API service
// import favoritesApi from '@/api/favorites';

const route = useRoute();
const currentFundType = ref('');
const currentBoard = ref(route.params.board || 'consumption');

const timeIntervals = {
  '1W': '周K',
  '1M': '月K',
  '1Y': '年K'
};
const currentInterval = ref('1W');
const fundTypes = ref([]);
const fundInfo = ref(null);
const chartData = ref(null);

const chartRef = ref(null);
let chartInstance = null;

// 获取并更新图表数据
const updateCharts = async () => {
  try {
    const response = await fundApi.getChartData('all', currentFundType.value, currentBoard.value);
    if (response.code === 200) {
      const { data } = response;
      fundInfo.value = data.fund_info;
      chartData.value = data;
      updateChart();
    }
  } catch (error) {
    console.error('Failed to update charts:', error);
  }
};

// 初始化基金类型
const initFundTypes = async () => {
  try {
    const response = await fundApi.getFundTypes(currentBoard.value);
    if (response.code === 200) {
      fundTypes.value = response.data.types;
      // 强制切换为新板块的第一个类型
      currentFundType.value = fundTypes.value[0];
    }
  } catch (error) {
    console.error('Failed to fetch fund types:', error);
  }
};

// 切换时间区间
const setInterval = (interval) => {
  currentInterval.value = interval;
};

// 监听时间区间和基金类型变化
watch([currentInterval, currentFundType], () => {
  updateCharts();
});

// 监听路由变化，自动切换板块
watch(
  () => route.params,
  async (params) => {
    currentBoard.value = params.board || 'consumption';
    await initFundTypes();
    await updateCharts();
  },
  { immediate: true }
);

// 组件挂载时初始化
onMounted(async () => {
  await initFundTypes();
  await updateCharts();
});

const updateChart = () => {
  if (!chartData.value || !chartData.value.klineData || !chartData.value.dates) return;
  if (!chartRef.value) return;

  if (chartInstance) {
    chartInstance.dispose();
  }
  chartInstance = echarts.init(chartRef.value);

  let klineData = chartData.value.klineData;
  let dates = chartData.value.dates;

  if (currentInterval.value === '1W') {
    const weekData = groupByWeek(klineData);
    klineData = weekData;
    dates = weekData.map(d => d.trade_date);
  } else if (currentInterval.value === '1M') {
    const monthData = groupByMonth(klineData);
    klineData = monthData;
    dates = monthData.map(d => d.trade_date);
  } else if (currentInterval.value === '1Y') {
    const yearData = groupByYear(klineData);
    klineData = yearData;
    dates = yearData.map(d => d.trade_date);
  }

  const kline = klineData.map(item => [
    item.open, item.close, item.low, item.high
  ]);
  const volumes = klineData.map((item, idx) => [
    idx, item.vol, item.close > item.open ? 1 : -1
  ]);


  const option = {
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis' },
    legend: { data: ['K线', '成交量'], textStyle: { color: '#eee' } },
    grid: [
      { // 主图
        left: '10%',
        right: '8%',
        top: 60,
        height: '58%',
        bottom: '22%' // 让主图和副图有间隔
      },
      { // 成交量
        left: '10%',
        right: '8%',
        top: '82%',
        height: '12%'
      }
    ],
    xAxis: [
      {
        type: 'category',
        data: dates,
        scale: true,
        boundaryGap: false,
        axisLine: { lineStyle: { color: '#888' } },
        axisLabel: {
          color: '#eee',
          formatter: function (value) {
            return value;
          }
        },
        axisTick: { show: false },
        splitLine: { show: false }
      },
      {
        type: 'category',
        gridIndex: 1,
        data: dates,
        scale: true,
        boundaryGap: false,
        axisLine: { lineStyle: { color: '#888' } },
        axisLabel: {
          color: '#eee',
          formatter: function (value) {
            return value;
          }
        },
        axisTick: { show: true },
        splitLine: { show: false }
      }
    ],
    yAxis: [
      {
        scale: true,
        splitArea: { show: true },
        axisLabel: { color: '#eee' }
      },
      {
        scale: true,
        gridIndex: 1,
        splitNumber: 2,
        axisLabel: { color: '#eee' }
      }
    ],
    dataZoom: [
      { type: 'inside', xAxisIndex: [0, 1], start: 80, end: 100 },
      { show: true, xAxisIndex: [0, 1], type: 'slider', top: '96%', start: 80, end: 100 }
    ],
    series: [
      {
        name: 'K线',
        type: 'candlestick',
        data: kline,
        itemStyle: {
          color: '#ec0000',
          color0: '#00da3c',
          borderColor: '#8A0000',
          borderColor0: '#008F28'
        }
      },
      {
        name: '成交量',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: volumes,
        itemStyle: { color: '#7fbe9e' }
      }
    ]
  };

  if (currentInterval.value === '1Y') {
    // 年K美化
    option.series[0].barWidth = 20; // K线更细
    option.series[1].barWidth = 20; // 成交量更细
    option.xAxis[0].axisLabel.fontSize = 16; // x轴字体大一点
    option.xAxis[1].axisLabel.fontSize = 16;
    option.grid[0].left = '12%';
    option.grid[0].right = '6%';
    option.grid[1].left = '12%';
    option.grid[1].right = '6%';
    // 年K数据点少，可以让dataZoom全显示或直接隐藏
    option.dataZoom[0].show = false;
    option.dataZoom[1].show = false;
  }

  chartInstance.setOption(option);
  window.addEventListener('resize', () => chartInstance && chartInstance.resize());
};

// 重置K线缩放
const resetKlineZoom = () => {
  updateChart();
};

function groupByWeek(data) {
  if (!data || data.length === 0) return [];
  const sorted = [...data].sort((a, b) => new Date(a.trade_date) - new Date(b.trade_date));
  const weekMap = new Map();

  sorted.forEach(d => {
    const date = new Date(d.trade_date);
    const day = date.getDay();
    const monday = new Date(date);
    monday.setDate(date.getDate() - ((day + 6) % 7));
    const mondayStr = monday.toISOString().slice(0, 10);

    if (!weekMap.has(mondayStr)) weekMap.set(mondayStr, []);
    weekMap.get(mondayStr).push(d);
  });

  const result = [];
  for (const [monday, arr] of weekMap.entries()) {
    arr.sort((a, b) => new Date(a.trade_date) - new Date(b.trade_date));
    result.push({
      trade_date: monday,
      open: arr[0].open,
      close: arr[arr.length - 1].close,
      high: Math.max(...arr.map(d => d.high)),
      low: Math.min(...arr.map(d => d.low)),
      vol: arr.reduce((sum, d) => sum + (d.vol || 0), 0),
    });
  }
  result.sort((a, b) => a.trade_date.localeCompare(b.trade_date));
  return result;
}

function groupByMonth(data) {
  if (!data || data.length === 0) return [];
  const sorted = [...data].sort((a, b) => new Date(a.trade_date) - new Date(b.trade_date));
  const monthMap = new Map();

  sorted.forEach(d => {
    const date = new Date(d.trade_date);
    const month = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0');
    if (!monthMap.has(month)) monthMap.set(month, []);
    monthMap.get(month).push(d);
  });

  const result = [];
  for (const [month, arr] of monthMap.entries()) {
    arr.sort((a, b) => new Date(a.trade_date) - new Date(b.trade_date));
    result.push({
      trade_date: month, // x轴用YYYY-MM
      open: arr[0].open,
      close: arr[arr.length - 1].close,
      high: Math.max(...arr.map(d => d.high)),
      low: Math.min(...arr.map(d => d.low)),
      vol: arr.reduce((sum, d) => sum + (d.vol || 0), 0),
      amount: arr.reduce((sum, d) => sum + (d.amount || 0), 0)
    });
  }
  result.sort((a, b) => a.trade_date.localeCompare(b.trade_date));
  return result;
}

function groupByYear(data) {
  if (!data || data.length === 0) return [];
  const yearMap = new Map();
  data.forEach(d => {
    const date = new Date(d.trade_date);
    const year = String(date.getFullYear());
    if (!yearMap.has(year)) yearMap.set(year, []);
    yearMap.get(year).push(d);
  });
  const result = [];
  for (const [year, arr] of yearMap.entries()) {
    arr.sort((a, b) => new Date(a.trade_date) - new Date(b.trade_date));
    result.push({
      trade_date: year, // x轴用YYYY
      open: arr[0].open,
      close: arr[arr.length - 1].close,
      high: Math.max(...arr.map(d => d.high)),
      low: Math.min(...arr.map(d => d.low)),
      vol: arr.reduce((sum, d) => sum + (d.vol || 0), 0),
      amount: arr.reduce((sum, d) => sum + (d.amount || 0), 0)
    });
  }
  result.sort((a, b) => a.trade_date.localeCompare(b.trade_date));
  return result;
}

// Function to add current fund to favorites
const addToFavorites = async () => {
  const userId = localStorage.getItem('user_id'); // **重要：请根据您的实际认证实现获取用户ID**
  if (!userId) {
    alert('请先登录以使用自选功能。');
    return;
  }

  if (!fundInfo.value || !fundInfo.value.ts_code) {
    alert('无法获取基金信息，请稍后再试。');
    return;
  }

  try {
    // Replace with your actual API call to backend favorites add endpoint
    const response = await axios.post('/api/v1/favorites/add', {
      user_id: userId,
      item_type: 'fund', // Indicate item type is fund
      item_code: fundInfo.value.ts_code,
      // Add board and category
      board: currentBoard.value,
      category: currentFundType.value
    });

    if (response.data.code === 200) {
      alert('添加自选成功！');
      // Optionally, update a state variable to indicate this item is now favorited
    } else if (response.data.code === 409) {
      alert(response.data.message); // Item already in favorites
    } else {
      alert('添加自选失败: ' + response.data.message);
    }
  } catch (error) {
    console.error('Error adding to favorites:', error);
    alert('添加自选失败，请检查网络或稍后再试。');
  }
};
</script>

<style scoped>
.dashboard-root {
  width: 100%;
  height: 100%;
  /* background: #181A20; Reverted to dark background */
  padding: 0;
  margin: 0;
  color: #ecf0f1; /* Reverted to light text */
}
.row, .col-12, .card, .card-header, .card-body, .d-flex, .fund-type-selector, .time-controls {
  margin-top: 0 !important;
  padding-top: 0 !important;
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
  margin-left: 0 !important;
  margin-right: 0 !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}
.py-2, .mb-2, .g-3, .px-4 {
  padding-top: 0 !important;
  padding-bottom: 0 !important;
  margin-bottom: 0 !important;
  margin-top: 0 !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}
.bg-dark {
  background-color: #1a1a1a !important; /* Reverted to dark background */
}

.card, .card-header, .card-body {
  border: none !important; /* Reverted to no border */
  background: transparent !important; /* Reverted to transparent */
  box-shadow: none !important; /* Reverted shadow */
}

.card {
  background-color: #242424; /* Reverted to dark background */
  transition: transform 0.2s, box-shadow 0.2s;
}

.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.2); /* Reverted hover shadow */
}

.card-body {
  height: 350px;
}

.form-select {
  background-color: #242424; /* Reverted to dark background */
  color: #e0e0e0; /* Reverted to light text */
  border-color: #444; /* Reverted to dark border */
}

.btn-outline-secondary {
  color: #e0e0e0; /* Reverted to light text */
  border-color: #444; /* Reverted to dark border */
}

.btn-outline-secondary:hover,
.btn-outline-secondary.active {
  background-color: #444; /* Reverted to dark background */
  color: #fff; /* Reverted to white text */
}

.card-title {
  color: #fff !important; /* Reverted to white text */
  font-weight: bold;
  text-shadow: 0 1px 4px #000; /* Reverted text shadow */
}

.text-muted {
  color: #b0b0b0 !important; /* Reverted to gray text */
}
.text-primary {
  color: #4fc3f7 !important; /* Reverted to teal */
}
.text-success {
  color: #7CFC00 !important; /* Reverted to green */
}
.text-white {
  color: #fff !important; /* Reverted to white */
}
.fund-info-item span {
  font-weight: bold;
  letter-spacing: 1px;
}
</style> 